<div class="layui-fluid layui-anim febs-anim" id="overView" lay-title="统计总览">
    <div class="febs-container layui-card">
        <div class="layui-card-body">
            <div id="query-project-form">
                <form method="post" class="layui-form" lay-filter="overView-table-from" id="overView-table-from">
                    <div class="layui-form-item">
                        <label class="layui-form-label">年份</label>
                        <div class="layui-input-block">
                            <input type="text" class="layui-input" name="year" id="date-select">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">月份</label>
                        <div class="layui-input-block">
                            <div id="month-select"></div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label" >统计方式</label>
                            <div class="layui-input-inline">
                                <input type="radio" lay-filter="statistical-by" name="statisticalMethod" value="1" title="总览" checked>
                                <input type="radio" lay-filter="statistical-by" name="statisticalMethod" value="2" title="明细">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">查询方式</label>
                            <div class="layui-input-inline">
                                <input type="radio" lay-filter="query-by" name="queryBy" value="1" title="按公司" checked>
                                <input type="radio" lay-filter="query-by" name="queryBy" value="2" title="按项目">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">预估项</label>
                            <div class="layui-input-inline">
                                <select name="ifEstimate" lay-verify="ifEstimate">
                                    <option value="-1">包含</option>
                                    <option value="0">不包含</option>
                                    <option value="1">只包含</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">月份明细</label>
                            <div class="layui-input-inline">
                                <input type="radio" name="ifShowMonth" value="1" title="是" checked>
                                <input type="radio" name="ifShowMonth" value="2" title="否">
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item" id="by-overview">
                        <label class="layui-form-label">统计科目</label>
                        <div class="layui-input-block">
                            <div id="standard-select"></div>
                        </div>
                    </div>
                    <div class="layui-form-item" id="by-detail" style="display: none">
                        <label class="layui-form-label">明细科目</label>
                        <div class="layui-input-block">
                            <select name="detailedStandard" lay-verify="detailed-standard">
                                <option value="1">收入</option>
                                <option value="2">费用</option>
                                <option value="3">成本</option>
                                <option value="4">税费</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item" id="by-company">
                        <label class="layui-form-label">公司名称</label>
                        <div class="layui-input-block">
                            <div id="company-select"></div>
                        </div>
                    </div>
                    <div class="layui-form-item" id="by-project" style="display: none">
                        <label class="layui-form-label">项目名称</label>
                        <div class="layui-input-block">
                            <div id="project-select"></div>
                        </div>
                    </div>
                    <hr class="layui-border-green">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">统计项</label>
                            <div class="layui-input-inline">
                                <input type="tel" name="title" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">查询</label>
                            <div class="layui-input-inline">
                                <div class="layui-btn layui-btn-sm layui-btn-primary febs-button-blue-plain table-action" id="query-overview">
                                    <i class="layui-icon">&#xe848;</i>
                                </div>
                                <div class="layui-btn layui-btn-sm layui-btn-primary febs-button-green-plain  table-action" id="reset">
                                    <i class="layui-icon">&#xe79b;</i>
                                </div>
                            </div>
                            <div class="layui-input-inline">
                                导出：
                                <div class="layui-btn  layui-btn-sm layui-btn-primary febs-button-green-plain" id="export">
                                    <i class="layui-icon">&#xe7a8;</i> 导出Excel
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div id="overviewTableDiv">
                <table lay-filter="overviewTable" id="overviewTable" lay-data="{id: 'overviewTable'}"></table>
            </div>
            <div id="detailTableDiv" style="display: none">
                <table lay-filter="detailTable" id="detailTable" lay-data="{id: 'detailTable'}"></table>
            </div>
        </div>
    </div>
</div>

<script data-th-inline="none" type="text/javascript">
    layui.use(['laydate', 'jquery', 'laydate', 'febs', 'form', 'eleTree', 'table', 'validate', 'xmSelect', 'layer', 'upload'], function () {
        let $ = layui.jquery,
            laydate = layui.laydate,
            febs = layui.febs,
            form = layui.form,
            table = layui.table,
            xmSelect = layui.xmSelect,
            companyXmSelect,
            monthXmSelect,
            projectXmSelect,
            standardXmSelect,
            $view = $('#overView'),
            $queryTableForm = $view.find('#overView-table-from'),
            $queryOverview = $view.find('#query-overview'),
            $reset = $view.find('#reset'),
            $export = $view.find('#export'),
            $layer = layui.layer,
            monthList = [],
            standardList = [],
            colIndex = [],
            monIndex = [],
            colNameList = [],
            sortObject,
            tableData = [],
            overviewTableIns,
            months = [],
            detailTableIns;

        laydate.render({
            elem: '#date-select',
            type: 'year',
            value: new Date().getFullYear()
        });

        form.render();

        getMonthList();
        initOverviewTable();
        initDetailTable();
        initColIndex();

        function initColIndex() {
            for (let i = 0; i < 500; i++) {
                colIndex.push('col' + (i + 1))
                monIndex.push('mon' + (i + 1))
            }
        }

        function getMonthList() {
            for (let i = 1; i <= 12; i++) {
                monthList.push({ name: i + '月', value: i})
            }
        }

        function initOverviewTable() {
            overviewTableIns = febs.table.init({
                elem: $view.find('#overviewTable'),
                id: 'overviewTable',
                url: ctx + 'overview/overviewTable',
                cols: [[]],
                cellMinWidth: 150,
                limit: 20
            });
        }

        function initDetailTable() {
            detailTableIns = febs.table.init({
                elem: $view.find('#detailTable'),
                id: 'detailTable',
                url: ctx + 'overview/detailTable',
                cols: [[]],
                cellMinWidth: 150,
                limit: 100
            });
        }

        function getQueryParams() {
            let params = $queryTableForm.serializeJson();
            params.invalidate_ie_cache = new Date();
            return params;
        }

        form.on('radio(statistical-by)', function (data) {
            const byOverview = document.getElementById('by-overview');
            const byDetail = document.getElementById('by-detail');
            const overviewTable = document.getElementById('overviewTableDiv')
            const detailTable = document.getElementById('detailTableDiv')
            if (data.value === '1') {
                byOverview.style.display = ''
                byDetail.style.display = 'none'
                overviewTable.style.display = ''
                detailTable.style.display = 'none'
            } else {
                byOverview.style.display = 'none'
                byDetail.style.display = ''
                overviewTable.style.display = 'none'
                detailTable.style.display = ''
            }
        });

        form.on('radio(query-by)', function (data) {
            const byCompany = document.getElementById('by-company');
            const byProject = document.getElementById('by-project');
            if (data.value === '1') {
                byCompany.style.display = ''
                byProject.style.display = 'none'
            } else {
                byCompany.style.display = 'none'
                byProject.style.display = ''
            }
        });

        $queryOverview.on('click', function () {
            let params = $queryTableForm.serializeJson();
            if (!params.year) {
                febs.alert.error("请选择年份");
                return;
            }
            if (!params.month) {
                febs.alert.error("请选择月份");
                return;
            }
            if (params.statisticalMethod === '1' && params.standardId === '') {
                febs.alert.error("请选择统计科目");
                return;
            }
            if (params.queryBy === '1' && params.companyId === '') {
                febs.alert.error("请选择公司");
                return;
            }
            if (params.queryBy === '2' && params.projectId === '' ) {
                febs.alert.error("请选择项目");
                return;
            }
            const preMonths = params.month.split(',')
            months = []
            for (let i = 1; i <= 12; i++) {
                if (preMonths.indexOf(i.toString()) !== -1) {
                    months.push(i)
                }
            }
            if (params.statisticalMethod === '1') {
                colNameList = []    // 后端导出keys
                colNameList.push('统计项')
                let colList = []
                colList.push({ field: 'key', title: '序号', width: 60 })
                colList.push({ field: 'title', title: '统计项' })
                let standardIds = params.standardId.split(',')
                let cnt = 0
                standardIds.forEach(e => {
                    for (let i = 0; i < standardList.length; i++) {
                        if (standardList[i].value === parseInt(e)) {
                            colList.push({ field: colIndex[cnt], title: standardList[i].name, sort: true })
                            colNameList.push(standardList[i].name)
                            if (params.ifShowMonth === '1') {
                                for (let j = 0; j < months.length; j++) {
                                    colList.push({ field: monIndex[cnt * months.length + j], title: months[j] + '月' })
                                    colNameList.push(months[j] + '月')
                                }
                            }
                            cnt++
                            break;
                        }
                    }
                })
                const cols = [colList]
                overviewTableIns.reload({where: getQueryParams(), page: {curr: 1}, cols: cols});
            } else {
                let colList = [{title: '序号', field: 'key', width: 60},
                    {title: '明细科目', field: 'subName'},
                    {title: '金额', field: 'cost'}]
                if (params.ifShowMonth === '1') {
                    for (let month of months) {
                        colList.push({title: month + '月', field: month})
                    }
                }
                const cols = [colList]
                detailTableIns.reload({where: getQueryParams(), page: {curr: 1}, cols: cols});
            }
        });

        table.on('sort(overviewTable)', function (obj) {
            sortObject = obj;
            overviewTableIns.reload({
                initSort: obj,
                where: $.extend(getQueryParams(), {
                    field: obj.field,
                    order: obj.type
                })
            });
        });

        $reset.on('click', function () {
            form.val('overView-table-from', {title: ''})
        })

        $export.on('click', function () {
            const param = $queryTableForm.serializeJson()
            const statisticalMethod = param.statisticalMethod
            let data = statisticalMethod === '1' ? table.cache.overviewTable : table.cache.detailTable
            if (data.length === 0) {
                febs.alert.error("表中无数据，不可导出");
                return
            }
            const params = {}
            params.dataStr = JSON.stringify(data)
            let col2 = '明细科目,金额'
            if (param.ifShowMonth === '1') {
                for (let month of months) {
                    col2 += ',' + month + '月'
                }
            }
            params.cols = statisticalMethod === '1' ? colNameList.join(',') : col2
            params.statisticalMethod = statisticalMethod
            params.ifShowMonth = param.ifShowMonth
            params.month = param.month
            const fileName = statisticalMethod === '1' ? '总览统计.xlsx' : '明细统计.xlsx'
            febs.download(ctx + 'overview/export', params, fileName);
        })

        monthXmSelect = xmSelect.render({
            el: '#month-select',
            toolbar: {show: true},
            name: 'month',
            theme: {color: '#52c41a'},
            prop: {
                name: 'name',
                value: 'value'
            },
            height: 450,
            data: monthList
        });

        standardXmSelect = xmSelect.render({
            el: '#standard-select',
            toolbar: {show: true},
            filterable: true,
            autoRow: true,
            theme: {color: '#9202f8'},
            height: 260,
            name: 'standardId',
            data: []
        });

        companyXmSelect = xmSelect.render({
            el: '#company-select',
            toolbar: {show: true},
            filterable: true,
            autoRow: true,
            theme: {color: '#0270f8'},
            height: 260,
            name: 'companyId',
            data: []
        });

        projectXmSelect = xmSelect.render({
            el: '#project-select',
            toolbar: {show: true},
            filterable: true,
            autoRow: true,
            theme: {color: '#0270f8'},
            height: 260,
            name: 'projectId',
            data: []
        });

        febs.get(ctx + 'company', null, function (result) {
            let companyList = result.data;
            let data = [];
            for (let i = 0; i < companyList.length; i++) {
                let e = {};
                e.value = companyList[i].id;
                e.name = companyList[i].companyName;
                data[i] = e;
            }
            companyXmSelect.update(
                {data: data}
            )
        });

        febs.get(ctx + 'project', null, function (result) {
            let projectList = result.data;
            let data = [];
            for (let i = 0; i < projectList.length; i++) {
                let e = {};
                e.value = projectList[i].id;
                e.name = projectList[i].projectName;
                data[i] = e;
            }
            projectXmSelect.update(
                {data: data}
            )
        });

        febs.post(ctx + 'overview/getStatisticsStandard', null, function (result) {
            // 对应数据库科目Id
            let headerStandard = [{ value: 2, name: '收入'}, { value: 63, name: '费用'}, { value: 72, name: '成本'}, { value: 76, name: '税费' }]
            let dataList = result.data;
            let data = [];
            headerStandard.forEach(e => { data.push(e) })
            dataList.forEach(e => {data.push({ value: e.id, name: e.name })})
            standardList = data
            standardXmSelect.update({data: data})
        });
    });
</script>